package com.leyou.cart.service;

import com.leyou.cart.domain.Cart;
import com.leyou.common.auth.domain.UserHolder;
import com.leyou.common.exception.domain.ExceptionEnum;
import com.leyou.common.exception.domain.LyException;
import com.leyou.common.uploadimgs.LyConstants;
import com.leyou.common.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CartService{
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加购物车
     * @param cart
     */
    public void addCart(Cart cart) {
        try {
            //先获取当前用户的id
            Long userId = UserHolder.getUserId();
            //得到当前用户在购物车中的key
            String userKey = LyConstants.USER_CART_KEY_PRE+userId;
            //通过当前用户的购物车的key，获取到购物车的hashMap
            BoundHashOperations<String, String, String> userCartHash = redisTemplate.boundHashOps(userKey);
            //获取当前新添加的购物车的id，skuId
            String hashKey = cart.getSkuId().toString();
            //通过购物车对象的id，来查看当前购物车中是否包含新添加的购物车对象
            Boolean hasKey = userCartHash.hasKey(hashKey);
            //如果有，则修改购物车中的商品数量
            if(hasKey){
                //先得到redis中原来的当前sku的购物车对象
                Cart redisCart = JsonUtils.toBean(userCartHash.get(hashKey), Cart.class);
                //将购物车中的cart对象的数量合并到新添加的购物车对象中
                cart.setNum(cart.getNum()+redisCart.getNum());
            }
            //保存购物车
            userCartHash.put(hashKey, JsonUtils.toString(cart));
        }catch (Exception e){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

    }

    /**
     * 查询购物车
     * @return
     */

    public List<Cart> findCarts() {
        //获取redis中当前用户的购物车key
        String userKey = LyConstants.USER_CART_KEY_PRE+UserHolder.getUserId();
        //判断当前用户是否有购物车
        if(!redisTemplate.hasKey(userKey)){
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        //判断当前用户购物车中是否有数据
        BoundHashOperations<String, String, String> hashCart = redisTemplate.boundHashOps(userKey);
        Map<String, String> entries = hashCart.entries();
        if(entries.size()==0){
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        //如果有数据获取到map所有的value
        List<Cart> carts = entries.values()
                .stream()
                .map(cartStr -> JsonUtils.toBean(cartStr, Cart.class))
                .collect(Collectors.toList());
        return carts;
    }

    /**
     * 合并购物车
     * @param carts
     */
    public void addCarts(List<Cart> carts) {
        for (Cart cart : carts) {
            addCart(cart);
        }
    }
}
